import { Injectable, Inject, BadRequestException } from '@nestjs/common';
import { FriendAddDto } from './dto/add-friendship.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { User } from '@prisma/client';

@Injectable()
export class FriendshipService {

    @Inject(PrismaService)
    private prismaService: PrismaService


    async getFriendship(userId: number, name: string) {
        const friends = await this.prismaService.friendship.findMany({
            where: {
                OR: [
                    {
                        userId: userId
                    },
                    {
                        friendId: userId
                    }
                ]
            }
        });

        // 确保id唯一
        const set = new Set<number>();
        for (let i = 0; i < friends.length; i++) {
            set.add(friends[i].userId)
            set.add(friends[i].friendId)
        }

        // 过滤掉userId
        const friendIds = [...set].filter(item => item !== userId);

        const res = [];

        for (let i = 0; i < friendIds.length; i++) {
            const user = await this.prismaService.user.findUnique({
                where: {
                    id: friendIds[i],
                },
                select: {
                    id: true,
                    username: true,
                    nickName: true,
                    email: true
                }
            })
            res.push(user)
        }
        const filteredRes = name ? res.filter((item: User) => item.nickName.includes(name)) : res;
        return filteredRes;

    }

    //好友请求记录
    async add(friendAddDto: FriendAddDto, userId: number) {
        const friend = await this.prismaService.user.findUnique({
            where:{
                username:friendAddDto.username
            }
        });
        if(!friend){
            throw new BadRequestException('要添加的username不存在')
        }
        if(friend.id === userId){
            throw new BadRequestException('不能添加自己为好友')
        }

        const found = await this.prismaService.friendship.findMany({
            where:{
                userId,
                friendId:friend.id
            }
            }
        )
        if(found.length){
            throw new BadRequestException('该好友已添加')
        }

        return await this.prismaService.friendRequest.create({
            data: {
                fromUserId: userId,
                toUserId: friend.id,
                reason: friendAddDto.reason,
                status: 0
            }
        })
    }


    //获取好友申请列表的实现
    async list(userId: number) {
        // return this.prismaService.friendRequest.findMany({
        //     where: {
        //         fromUserId: userId
        //     }
        // }) 
        const fromMeRequest = await this.prismaService.friendRequest.findMany({
            where: {
                fromUserId: userId
            }
        })
    
        const toMeRequest =  await this.prismaService.friendRequest.findMany({
            where: {
                toUserId: userId
            }
        })
    
        const res = {
            toMe: [],
            fromMe: []
        }
    
        for (let i = 0; i < fromMeRequest.length; i++) {
            const user = await this.prismaService.user.findUnique({
                where: {
                    id: fromMeRequest[i].toUserId
                },
                select: {
                    id: true,
                    username: true,
                    nickName: true,
                    email: true,
                    headPic: true,
                    createTime: true
                }
            })
            res.fromMe.push({
                ...fromMeRequest[i],
                toUser: user
            })
        }
    
        for (let i = 0; i < toMeRequest.length; i++) {
            const user = await this.prismaService.user.findUnique({
                where: {
                    id: toMeRequest[i].fromUserId
                },
                select: {
                    id: true,
                    username: true,
                    nickName: true,
                    email: true,
                    headPic: true,
                    createTime: true
                }
            })
            res.toMe.push({
                ...toMeRequest[i],
                fromUser: user
            })
        }
    
        return res;
        
    }

    //同意添加好友
    async agree(friendId: number, userId: number) {

        await this.prismaService.friendRequest.updateMany({
            where: {
                fromUserId: friendId,
                toUserId: userId,
                status: 0
            },
            data: {
                status: 1
            }
        })

        //是否已经存在好友关系
        const res = await this.prismaService.friendship.findMany({
            where: {
                userId,
                friendId
            }
        })

        if (!res.length) {
            await this.prismaService.friendship.create({
                data: {
                    userId,
                    friendId
                }
            })
        }
        return '添加成功'
    }


    //拒绝添加好友
    async reject(friendId: number, userId: number) {
        await this.prismaService.friendRequest.updateMany({
            where: {
                fromUserId: friendId,
                toUserId: userId,
                status: 0
            },
            data: {
                status: 2
            }
        })
        return '已拒绝'
    }


    async remove(friendId: number, userId: number) {
        await this.prismaService.friendship.deleteMany({
            where: {
                userId,
                friendId,
            }
        })
        return '删除成功'
    }
}


/**
 * 8.15 支持按昵称搜索好友，但过滤语句有点问题
 * 更新之后必须传入name参数才会进行过滤，否则返回全部好友列表
 * 
 * 8.26 修改好友请求列表接口
 * 用户发出的好友请求、发给用户的好友请求，都应该展示出来。
 * 并且接口应该顺带把用户信息也给查出来返回。
 */
